package com.longrise.android.byjk.plugins.course.batchbuy.batchbuyconfirm;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.AllCourseChildBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.course.pay.BatchPaymentActivity;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.eventbean.PayEventBean;
import com.longrise.common.utils.UmengStatisticsUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * Created by callxkj on 2017/11/17.
 * 批量购买 订单确认
 */

public class BatchbuyConfirmActivity extends BaseActivity2 implements View.OnClickListener {

    public static final String SELECTLIST = "selectlist";
    public static final String ORDERTYPE = "ordertype"; //订单的类型 购买多个 购买全部
    public static final String BUY_ALL = "buyall"; //购买全部
    public static final String BUY_MULTIPLE = "buymultiple"; //购买多个

    private RecyclerView mRcv;
    private ArrayList<String> mCourseids = new ArrayList<>();
    private BatchbuyConfirmRcvAdapter mAdapter;
    private TextView mTv_sfk;
    private TextView mTv_price;
    private View mfootView;
    private Button mBtConfirm;
    private TextView mtv_kcsl;
    private TextView mtv_kczj;
    private TextView mtv_zklj;
    private TextView mtv_zkl;
    private TextView mtv_ckqbkc;
    private String mOrderType;  //订单类型
    private EntityBean[] mAllcourses;
    private View mDefault_view;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_batchbuyconfirm;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        setToolbarTitle("订单确认");
        mRcv = (RecyclerView) findViewById(R.id.batchbuyconfirm_rcv);
        mTv_sfk = (TextView) findViewById(R.id.batchbuyconfirm_tv_sfk);
        mTv_price = (TextView) findViewById(R.id.batchbuyconfirm_buy_tv);
        mBtConfirm = (Button) findViewById(R.id.batchbuyconfirm_buy_bt);
        //预加载页面
        mDefault_view = findViewById(R.id.batchbuyconfirm_default);
        getIntentData();
        initRcv();
        initEvent();

        if (BUY_MULTIPLE.equals(mOrderType)) {
            getOrderMsg();
        } else {
            getAllOrderMsg();
        }

    }

    @Override
    public void onToolbarBackClick() {
        UmengStatisticsUtil.onEvent("buy_confirm_return");
        finish();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        mOrderType = extras.getString(ORDERTYPE);
        if (BUY_ALL.equals(mOrderType)) { //购买全部

        } else if (BUY_MULTIPLE.equals(mOrderType)) { //购买多个
            ArrayList<AllCourseChildBean> coursebeans = intent.getParcelableArrayListExtra(SELECTLIST);
            if (coursebeans == null) {
                return;
            }
            for (AllCourseChildBean bean : coursebeans) {
                String courseid = bean.getCourseid();
                mCourseids.add(courseid);
            }
        }
    }

    private void initRcv() {
        //headView
        View headView = View.inflate(mContext, R.layout.item_confirmorder_header, null);
        mfootView = View.inflate(mContext, R.layout.item_confirmorder_footer, null);
        mAdapter = new BatchbuyConfirmRcvAdapter();
        mAdapter.addHeaderView(headView);
        mAdapter.addFooterView(mfootView);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        mRcv.setLayoutManager(manager);
        mRcv.setAdapter(mAdapter);
    }

    private void initEvent() {
        mBtConfirm.setOnClickListener(this);
    }

    @Override
    public void reload() {
        super.reload();
        if (BUY_MULTIPLE.equals(mOrderType)) {
            getOrderMsg();
        } else {
            getAllOrderMsg();
        }
    }

    /**
     * 获取订单数据
     * state 0:获取3条课程数据   1:获取全部的课程数据
     */
    private void getOrderMsg() {
        EntityBean bean = new EntityBean();
        bean.set("groupids", mCourseids);
        bean.set("state", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_pay_giveDiscountByPlanId", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            if (result != null) {
                                EntityBean bean = (EntityBean) result;
                                int resultstate = bean.getInt("resultstate");
                                if (resultstate == 1) {
                                    EntityBean resultBean = bean.getBean("result");
                                    parseResult(resultBean);
                                } else {
                                    showToast(bean.getString("resultdesc"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showNonNetPage();
                        }
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        showNonNetPage();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        mDefault_view.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 全面部购买
     * state 0:获取3条课程数据   1:获取全部的课程数据
     */
    private void getAllOrderMsg() {
        EntityBean bean = new EntityBean();
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("state", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_course_allCoursePay", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            if (result != null) {
                                EntityBean bean = (EntityBean) result;
                                int resultstate = bean.getInt("resultstate");
                                if (resultstate == 1) {
                                    EntityBean resultBean = bean.getBean("result");
                                    parseResult(resultBean);
                                } else {
                                    showToast(bean.getString("resultdesc"));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showNonNetPage();
                        }
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        showNonNetPage();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        mDefault_view.setVisibility(View.GONE);
                    }
                });
    }

    /**
     * 解析订单数据
     */
    private void parseResult(EntityBean bean) {
        int coursenum = bean.getInt("coursenum"); //购买的课程数量
        String allcourseprice = bean.getString("allcourseprice"); //课程总价
        String discountamount = bean.getString("discountamount"); //折扣立减
        String discountrate = bean.getString("discountrate"); //折扣率
        String discountprice = bean.getString("discountprice"); //折后价
        mAllcourses = bean.getBeans("allcourse");
        assembleFootView(coursenum, allcourseprice, discountamount, discountrate);
        if (mAllcourses != null && mAllcourses.length > 3) {
            //刚开始只显示3个数据
            EntityBean[] firstCourses = new EntityBean[]{mAllcourses[0], mAllcourses[1], mAllcourses[2]};
            mAdapter.setDatas(firstCourses);
        } else {
            mAdapter.setDatas(mAllcourses);
        }
        mCourseids.clear();
        for (int x = 0; x < mAllcourses.length; x++) {
            EntityBean allcourse = mAllcourses[x];
            String groupid = allcourse.getString("groupid");
            mCourseids.add(groupid);
        }
        mTv_price.setText("¥" + discountprice);
    }


    /**
     * @param coursenum      购买的课程数量
     * @param allcourseprice 课程总价
     * @param discountamount 折扣立减
     * @param discountrate   折扣率
     * @return footview
     */
    private void assembleFootView(int coursenum, String allcourseprice, String discountamount,
                                  String discountrate) {
        mtv_kcsl = (TextView) mfootView.findViewById(R.id.item_confirm_order_footer_kcsl_tv);
        mtv_kczj = (TextView) mfootView.findViewById(R.id.item_confirm_order_footer_kczj_tv);
        mtv_zklj = (TextView) mfootView.findViewById(R.id.item_confirm_order_footer_zklj_tv);
        mtv_zkl = (TextView) mfootView.findViewById(R.id.item_confirm_order_footer_zkl_tv);
        mtv_ckqbkc = (TextView) mfootView.findViewById(R.id.item_confirm_order_footer_ckqbkc_tv);

        //一共打折减的价格
        double discountamountd = Double.parseDouble(discountamount);
        if (discountamountd == 0) { //没有打折
            mtv_zklj.setText("无");
            mtv_zklj.setTextColor(Color.parseColor("#999999"));
            mtv_zkl.setText("无");
            mtv_zkl.setTextColor(Color.parseColor("#999999"));
            mTv_sfk.setText("实付款：");
        } else {
            mtv_zklj.setText("- ¥" + discountamount);
            mtv_zklj.setTextColor(Color.parseColor("#FC0000"));
            mtv_zkl.setText(discountrate);
            mtv_zkl.setTextColor(Color.parseColor("#FC0000"));

            mTv_sfk.setText("折后价：");
        }
        mtv_kcsl.setText(coursenum + "");
        mtv_kczj.setText("¥" + allcourseprice);
        if (coursenum <= 3) { //课程数量大于三 则显示点击查看更多课程
            mtv_ckqbkc.setVisibility(View.GONE);
            mAdapter.setLastLineVisiable(false);
        } else {
            mAdapter.setLastLineVisiable(true);
            mtv_ckqbkc.setText("查看全部" + coursenum + "个课程");
            mtv_ckqbkc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UmengStatisticsUtil.onEvent("buy_confirm_check");
                    toShowMoreCourse();
                }
            });

        }
    }

    /**
     * 显示更多数据
     */
    private void toShowMoreCourse() {
        mtv_ckqbkc.setVisibility(View.GONE);
        mAdapter.setLastLineVisiable(false);
        mAdapter.setDatas(mAllcourses);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.batchbuyconfirm_buy_bt:
                UmengStatisticsUtil.onEvent("buy_confirm_submit");
                toPay();
                break;
        }
    }

    /**
     * 跳转至支付界面支付
     */
    private void toPay() {
        Intent intent = new Intent(this, BatchPaymentActivity.class);
        intent.putStringArrayListExtra(BatchPaymentActivity.COURSEID_LIST, mCourseids);
        intent.putExtra(BatchPaymentActivity.BUY_TYPE,2); //购买途径 1-单个购买 2-批量购买 3- 团购
        intent.putExtra(BatchPaymentActivity.COURSENUM, mtv_kcsl.getText().toString().trim());
        intent.putExtra(BatchPaymentActivity.COURSEPRICE, mTv_price.getText().toString().trim());
        intent.putExtra(BatchPaymentActivity.KCZJ, mtv_kczj.getText().toString().trim());
        intent.putExtra(BatchPaymentActivity.ZKLJ, mtv_zklj.getText().toString().trim());
        intent.putExtra(BatchPaymentActivity.ZKL, mtv_zkl.getText().toString().trim());
        startActivity(intent);
    }

    /**
     * 支付成功后关闭页面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPayResult(PayEventBean bean){
        if(bean.isClosePage()){
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            UmengStatisticsUtil.onEvent("buy_confirm_return");
        }
        return super.onKeyDown(keyCode, event);
    }
}
